from flask_sqlalchemy import SQLAlchemy
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash
import datetime

# 初始化数据库
db = SQLAlchemy()

# 用户-单词关联表
user_words = db.Table('user_words',
    db.Column('user_id', db.Integer, db.ForeignKey('user.id'), primary_key=True),
    db.Column('word_id', db.Integer, db.ForeignKey('word.id'), primary_key=True),
    db.Column('added_date', db.DateTime, default=datetime.datetime.utcnow)
)

class User(UserMixin, db.Model):
    """用户模型"""
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    password_hash = db.Column(db.String(128))
    created_at = db.Column(db.DateTime, default=datetime.datetime.utcnow)
    
    # 一对多关系：用户拥有多个词汇
    vocabulary = db.relationship('Word', secondary=user_words, 
                            backref=db.backref('users', lazy='dynamic'))
    
    def set_password(self, password):
        """设置密码哈希"""
        self.password_hash = generate_password_hash(password)
    
    def check_password(self, password):
        """验证密码"""
        return check_password_hash(self.password_hash, password)
    
    def add_word_to_vocab(self, word_text):
        """向用户词汇表添加单词"""
        word = Word.query.filter_by(text=word_text.lower()).first()
        if word is None:
            word = Word(text=word_text.lower())
            db.session.add(word)
        
        if word not in self.vocabulary:
            self.vocabulary.append(word)
    
    def get_vocabulary(self):
        """获取用户全部词汇"""
        return [word.text for word in self.vocabulary]
    
    def __repr__(self):
        return f'<User {self.username}>'


class Word(db.Model):
    """单词模型"""
    id = db.Column(db.Integer, primary_key=True)
    text = db.Column(db.String(100), unique=True, nullable=False)
    
    def __repr__(self):
        return f'<Word {self.text}>' 